import React, { useCallback } from 'react';
import { Upload, Image } from '@douyinfe/semi-ui';
import { UPLOAD_CONFIG } from '../constants';
import { useImageUpload } from '@/hooks/useImageUpload';
import styles from '../index.module.scss';

/**
 * 可复用的上传组件
 * @param {Object} props
 * @param {string} props.title - 上传标题
 * @param {string} props.uploadKey - 上传键值
 * @param {string} props.subtitle - 副标题
 * @param {string} props.currentMenuKey - 当前菜单键
 * @param {Function} props.onUpload - 上传处理函数
 * @param {Function} props.onHistoryClick - 历史文件点击处理
 * @param {Object} props.imgObj - 图片对象
 */
function UploadComponent({ 
  title, 
  uploadKey, 
  subtitle = "参考图", 
  currentMenuKey,
  onUpload,
  onHistoryClick,
  imgObj 
}) {
  const { handleUpload, uploading, progress, validateFile } = useImageUpload({
    onSuccess: (result) => {
      if (onUpload) {
        onUpload({ 
          url: result.url,
          uploadKey,
          type: 'single',
          file: null // 上传成功后不需要file对象
        });
      }
    },
    onError: (error) => {
      console.error('上传失败:', error);
    }
  });

  const handleCustomRequest = useCallback(async ({ file, onSuccess, onError }) => {
    try {
      // 验证文件
      const isValid = await validateFile(file);
      if (!isValid) {
        onError(new Error('文件验证失败'));
        return;
      }
      
      // 执行上传
      const result = await handleUpload(file);
      
      if (result.success) {
        onSuccess(result);
      } else {
        onError(result.error || new Error('上传失败'));
      }
    } catch (error) {
      onError(error);
    }
  }, [handleUpload, validateFile]);

  const handleHistoryClick = useCallback((e) => {
    onHistoryClick(e);
  }, [onHistoryClick]);

  const handleTextClick = useCallback((e) => {
    if (e.target.tagName !== 'SPAN') {
      e.stopPropagation();
      // 触发文件选择器
      const fileInput = e.currentTarget.closest('.semi-upload').querySelector('input[type="file"]');
      if (fileInput) {
        fileInput.click();
      }
    }
  }, []);

  const imageKey = `${currentMenuKey}_${uploadKey}`;
  const hasImage = imgObj[imageKey];
  const uploadClassName = `${styles.uploadSection} ${
    currentMenuKey === 'multi' ? styles.uploadMultiSize : styles.uploadFullSize
  }`;

  return (
    <Upload 
      {...UPLOAD_CONFIG} 
      className={uploadClassName} 
      customRequest={handleCustomRequest}
      onAcceptInvalid={() => {
        Toast.error({ content: '文件类型不支持，请重新选择文件', stack: true });
      }}
      disabled={uploading}
    >
      {hasImage ? (
        <div style={{ width: '100%', height: '100%', position: 'relative' }}>
          <Image
            style={{ width: '100%', height: '100%' }}
            src={hasImage}
            preview={false}
            draggable={false}
          />
          {uploading && (
            <div className={styles.uploadProgress}>
              <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
            </div>
          )}
        </div>
      ) : (
        <div className={styles.uploadPlaceholder}>
          {uploading ? (
            <div className={styles.uploadingState}>
              <div className={styles.uploadText}>上传中... {progress}%</div>
              <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
            </div>
          ) : (
            <>
              <div className={styles.uploadText} onClick={handleTextClick}>
                上传<span>「{title}」</span>{subtitle && subtitle}
              </div>
              <div className={styles.uploadText}>
                从<span onClick={handleHistoryClick}>「历史文件」</span>上传
              </div>
            </>
          )}
        </div>
      )}
    </Upload>
  );
}

export default UploadComponent;